package com.simple.cloud.sso.controller;

import cn.dev33.satoken.sso.SaSsoManager;
import cn.dev33.satoken.sso.config.SaSsoClientConfig;
import cn.dev33.satoken.sso.model.SaCheckTicketResult;
import cn.dev33.satoken.sso.processor.SaSsoClientProcessor;
import cn.dev33.satoken.sso.template.SaSsoUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Sa-Token-SSO Client端 Controller
 */
@Slf4j
@RestController
public class SsoClientController {

    // 首页
    @RequestMapping("/")
    public String index(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        String servletPath = request.getServletPath();
        log.warn("sso-client 的 / 请求路由，servletPath={},Authorization={}，isLogin = {}", servletPath, authorization, StpUtil.isLogin());
        return "<h2>Sa-Token SSO-Client 应用端</h2>" +
                "<p>当前会话是否登录：" + StpUtil.isLogin() + "</p>" +
                "<p><a href=\"javascript:location.href='/sso/login?back=' + encodeURIComponent(location.href);\">登录</a> " +
                "<a href=\"javascript:location.href='" + SaSsoManager.getClientConfig().splicingSloUrl() + "?back=' + encodeURIComponent(location.href);\">注销</a> </p>";
    }
    /*
     * SSO-Client端：处理所有SSO相关请求
     * 		http://{host}:{port}/sso/login			-- Client端登录地址，接受参数：back=登录后的跳转地址
     * 		http://{host}:{port}/sso/logout			-- Client端单点注销地址（isSlo=true时打开），接受参数：back=注销后的跳转地址
     * 		http://{host}:{port}/sso/logoutCall		-- Client端单点注销回调地址（isSlo=true时打开），此接口为框架回调，开发者无需关心
     */
    @RequestMapping("/sso/*")
    public Object ssoRequest(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        String servletPath = request.getServletPath();
        Object disputer = SaSsoClientProcessor.instance.dister();
        log.warn("sso-client 的 /sso/* 请求路由，servletPath={},Authorization={},返回值 ：{}", servletPath, authorization, disputer);
        return disputer;
    }


    // 当前是否登录
    @RequestMapping("/sso/isLogin")
    public Object isLogin() {
        return SaResult.data(StpUtil.isLogin());
    }

    // 返回SSO认证中心登录地址
    @RequestMapping("/sso/getSsoAuthUrl")
    public SaResult getSsoAuthUrl(String clientLoginUrl) {
        String serverAuthUrl = SaSsoUtil.buildServerAuthUrl(clientLoginUrl, "");
        return SaResult.data(serverAuthUrl);
    }

    // 根据ticket进行登录
    @RequestMapping("/sso/doLoginByTicket")
    public SaResult doLoginByTicket(String ticket) {
        SaCheckTicketResult ctr = SaSsoClientProcessor.instance.checkTicket(ticket, "/sso/doLoginByTicket");
        StpUtil.login(ctr.loginId, ctr.remainSessionTimeout);
        return SaResult.data(StpUtil.getTokenValue());
    }

    // 配置SSO相关参数
    @Autowired
    private void configSso(SaSsoClientConfig ssoClient) {

    }

    @ExceptionHandler
    public SaResult handlerException(Exception e) {
        log.error("sso-client 发生错误", e);
        return SaResult.error(e.getMessage());
    }

}
